import axios from 'axios'
// import qs from 'qs'
// import router from '@/router/index'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'
import storage from 'utils/storage'

const api = axios.create({
  baseURL: import.meta.env.DEV && import.meta.env.VITE_OPEN_PROXY === 'true' ? '/' : import.meta.env.VITE_APP_API_BASEURL,
  timeout: 100000,
  headers: {
    'Content-Type': 'application/json'
  }
})

api.interceptors.request.use(
  request => {
    /**
     * 全局拦截请求发送前提交的参数
     * 以下代码为示例，在请求头里带上 token 信息
     */
    const userStore = useUserStore()
    if (userStore.isLogin) {
      request.headers['Authorization'] = `Bearer ${userStore.token}`
    }
    if (request.method === 'get') {
      for (const i in request.params) {
        if (request.params[i] === '') {
          delete request.params[i]
        }
      }
    }
    // 是否将 POST 请求参数进行字符串化处理
    // if (request.method === 'post' && request.headers['Content-Type'] !== 'multipart/form-data') {
    //   request.data = qs.stringify(request.data)
    // }
    return request
  }
)

api.interceptors.response.use(
  response => {
    const userStore = useUserStore()
    if (response.status == 200) {
      return Promise.resolve(response.data)
    } else {
      if (response.data.code === '-2' || response.data.code === '-3') {
        ElMessage.error('需要重新登录')
        storage.local.remove('token')
        storage.local.remove('userInfo')
        userStore.SET_TOKEN('')
        location.reload()
        return
      }
      const NOT_TIPS_URL = ['/student/follow/summary/data/import']
      if (!NOT_TIPS_URL.includes(response.config.url)) {
        ElMessage.error(response.data.message || response.data.result)
      }
      return Promise.reject(response.data)
    }
  },
  async error => {
    let message = error.message
    // 401退出登录
    const arr = [403, 400]
    // console.log(error.response.status)
    console.log(error.response, error.response.data.message)
    if (arr.includes(error.response.status)) {
      message = error.response.data.message
    } else if (error.response.status === 401) {
      const userStore = useUserStore()
      ElMessage.error('需要重新登录')
      storage.local.remove('token')
      storage.local.remove('userInfo')
      userStore.SET_TOKEN('')
      location.reload()
      return Promise.reject(error)
    } else if (error.response.status === 500 || message == 'Network Error') {
      message = '网络故障'
    } else if (message.includes('timeout')) {
      message = '接口请求超时'
    } else   if (message.includes('Request failed with status code')) {
      message = '接口' + message.substr(message.length - 3) + '异常'
    }
    ElMessage({
      message,
      type: 'error'
    })
    return Promise.reject(error)
  }
)

export default api
